package org.jjche.mybatis.interceptor;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.jjche.common.vo.DataScopeVO;
import org.jjche.core.util.SecurityUtil;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * <p>
 * mybatis拦截器，
 * </p>
 *
 * @author miaoyj
 * @version 1.0.0-SNAPSHOT
 * @since 2020-07-14
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MyInterceptor implements Interceptor {
    /**
     * {@inheritDoc}
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        //设置部门编码
        sysDeptCode(sqlCommandType, parameter);
        return invocation.proceed();
    }

    /**
     * <p>
     * 设置部门编码
     * </p>
     *
     * @param sqlCommandType /
     * @param parameter      /
     */
    private void sysDeptCode(SqlCommandType sqlCommandType, Object parameter) {
        if (SqlCommandType.INSERT == sqlCommandType) {
            if (parameter != null) {
                String sysDeptCode = StrUtil.toCamelCase(DataScopeVO.sysDeptCode);
                Field field = ClassUtil.getDeclaredField(parameter.getClass(), sysDeptCode);
                if (field != null) {
                    field.setAccessible(true);
                    try {
                        field.set(parameter, SecurityUtil.getDeptCode());
                    } catch (IllegalAccessException e) {
                        StaticLog.error(e);
                        throw new RuntimeException(e);
                    }
                    field.setAccessible(false);
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setProperties(Properties properties) {
    }

}
